package com.czmini.cztest.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.czmini.cztest.common.ServiceException;
import com.czmini.cztest.constants.UserConstants;
import com.czmini.cztest.dao.ZcTestCaseMapper;
import com.czmini.cztest.dao.ZcTestJenkinsMapper;
import com.czmini.cztest.dao.ZcTestTaskCaseRelMapper;
import com.czmini.cztest.dao.ZcTestTaskMapper;
import com.czmini.cztest.dto.ResultDto;
import com.czmini.cztest.dto.task.AddZcTestTaskDto;
import com.czmini.cztest.dto.task.TestTaskDto;
import com.czmini.cztest.entity.ZcTestCase;
import com.czmini.cztest.entity.ZcTestJenkins;
import com.czmini.cztest.entity.ZcTestTask;
import com.czmini.cztest.entity.ZcTestTaskCaseRel;
import com.czmini.cztest.service.ZcTestUserTaskService;
import com.czmini.cztest.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @ProjectName: cztest
 * @Package: com.czmini.cztest.service.impl
 * @ClassName: ZcTestUserTaskServiceImpl
 * @Author: 还是那个橙子
 * @Description:
 * @Date: 2022/4/21 22:38
 * @Version: 1.0
 */
@Slf4j
@Service
public class ZcTestUserTaskServiceImpl implements ZcTestUserTaskService {
    @Autowired
    private ZcTestJenkinsMapper zcTestJenkinsMapper;
    @Autowired
    private ZcTestCaseMapper zcTestCaseMapper;
    @Autowired
    private ZcTestTaskMapper zcTestTaskMapper;
    @Autowired
    private ZcTestTaskCaseRelMapper zcTestTaskCaseRelMapper;

    /**
     * 新增测试任务
     * @param testTaskDto
     * @param tasktype
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
     public ResultDto<ZcTestTask> save(TestTaskDto testTaskDto, Integer tasktype) {
        // 输入测试命令
        StringBuilder testcommand = new StringBuilder();
        // 获取任务信息
        AddZcTestTaskDto teskTask = testTaskDto.getTeskTask();
        List<Integer> caselist = testTaskDto.getCaseIdlist(); // 获取用例id列表

        // 校验JENKINS
        ZcTestJenkins queryTestJenkins = new ZcTestJenkins();
        queryTestJenkins.setId(teskTask.getTestJenkinsId());
        queryTestJenkins.setCreateUserId(teskTask.getCreateUserId());

        ZcTestJenkins result = zcTestJenkinsMapper.selectOne(queryTestJenkins);
        if (result == null) {
            return ResultDto.fail("jenkins不存在");
        }
        //TODO 查询测试 用例列表
        List<ZcTestCase> zcTestCaseList = zcTestCaseMapper.selectByIds(StrUtil.list2IdsStr(caselist));
        // Todo 生成测试命令
        makeTestCommand(testcommand, result, zcTestCaseList);


        // 测试任务存库
        ZcTestTask zcTestTask = new ZcTestTask();
        zcTestTask.setName(teskTask.getName());
        zcTestTask.setTestJenkinsId(teskTask.getTestJenkinsId());
        zcTestTask.setCreateUserId(teskTask.getCreateUserId());
        zcTestTask.setRemark(teskTask.getRemark());

        zcTestTask.setTestCommand(testcommand.toString());
        zcTestTask.setTaskType(tasktype);
        zcTestTask.setCaseCount(caselist.size());
        zcTestTask.setStatus(UserConstants.STATUS_ZERO);
        zcTestTask.setCreateTime(new Date());
        zcTestTask.setUpdateTime(new Date());
        // 插入任务
        zcTestTaskMapper.insert(zcTestTask);

        if (Objects.nonNull(caselist) && caselist.size() > 0)  {
            // 插入 测试任务用例关联对象
            ArrayList<ZcTestTaskCaseRel> testTaskCaseList = new ArrayList<>();
            for (Integer testCaseId : caselist) {
                ZcTestTaskCaseRel testTaskCaseRel = new ZcTestTaskCaseRel();
                testTaskCaseRel.setTaskId(zcTestTask.getId());
                testTaskCaseRel.setCaseId(testCaseId);
                testTaskCaseRel.setCreateUserId(zcTestTask.getCreateUserId());
                testTaskCaseRel.setCreateTime(new Date());
                testTaskCaseRel.setUpdateTime(new Date());
                testTaskCaseList.add(testTaskCaseRel);
            }
            log.info("=====测试任务详情保存-落库入参====："+ JSONObject.toJSONString(testTaskCaseList));
            zcTestTaskCaseRelMapper.insertList(testTaskCaseList);
        }
        return ResultDto.success("成功", zcTestTask);
    }

    private void makeTestCommand(StringBuilder testCommand, ZcTestJenkins zcTestJenkins, List<ZcTestCase> zcTestCaseList) {
        //打印测试目录
        testCommand.append("pwd");
        testCommand.append("\n");
        if(Objects.isNull(zcTestJenkins)){
            throw new ServiceException("组装测试命令时，Jenkins信息为空");
        }
        if(Objects.isNull(zcTestCaseList) || zcTestCaseList.size()==0){
            throw new ServiceException("组装测试命令时，测试用例列表信息为空");
        }
        String runCommand = zcTestJenkins.getTestCommand();
        Integer commandRunCaseType = zcTestJenkins.getCommandRunCaseType();
        if(Objects.isNull(commandRunCaseType)){
            commandRunCaseType=1;
        }

        String systemTestCommand = zcTestJenkins.getTestCommand();
        if(StringUtils.isEmpty(systemTestCommand)){
            throw new ServiceException("组装测试命令时，运行的测试命令信息为空");
        }

        //设置 文本类型
        if(Objects.isNull(commandRunCaseType)){
            commandRunCaseType=1;
        }

        //设置 遍历测试数据
        if (commandRunCaseType == 1) {
            for (ZcTestCase zcTestCase : zcTestCaseList) {
            // 拼接测试命令 如mvntest 系统测试工具
                testCommand.append(runCommand);
                //拼装测试数据
                 testCommand.append(zcTestCase.getCaseData())
                .append("\n");
            }
        }
        //文件类型
        if (commandRunCaseType == 2) {
            //获取文件后缀
            String commandRunCaseSuffix = zcTestJenkins.getCommandRunCaseSuffix();
            if(StringUtils.isEmpty(commandRunCaseSuffix)){
                throw new ServiceException("组装测试命令且case为文件时，测试用例后缀名不能为空");
            }
            for (ZcTestCase zcTestCase : zcTestCaseList) {
                //拼装下载文件的curl命令
                makeCurlCommand(testCommand, zcTestCase, commandRunCaseSuffix);
                //拼接测试命令
                testCommand.append("\n");
                testCommand.append(systemTestCommand).append("");
                testCommand.append(zcTestCase.getCaseData()).append(".").append(commandRunCaseSuffix);
                testCommand.append(" || true ");
                testCommand.append("\n");

            }
        }
        log.info("testcommand==============="+testCommand);
    }

    /**
     * 拼装.curl命令
     * @param testCommand
     * @param zcTestCase
     * @param commandRunCaseSuffix
     */
    private void makeCurlCommand(StringBuilder testCommand, ZcTestCase zcTestCase, String commandRunCaseSuffix) {
        //通过curl命令获取测试数据并保存为文件
        testCommand.append("curl  ")
                .append("-o ");
        String caseName = zcTestCase.getCaseName();
        if(StringUtils.isEmpty(caseName)){
            caseName = "测试用例无测试名称";
        }
        testCommand.append(caseName)
                .append(".")
                .append(commandRunCaseSuffix)
                .append(" ${aitestBaseUrl}/testCase/data/")  // 测试平台的基础信息
                .append(zcTestCase.getId())
                .append(" -H \"token: ${token}\" ");  // 放置token
        //.append(" -H \"token: ${token}\" ");  // 放置tcokies
        //本行命令执行失败，继续运行下面的命令行
        testCommand.append(" || true");
        testCommand.append("\n");

    }
}
